package wang.chunfan.mybatis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import wang.chunfan.mybatis.log.LogProducer;
import wang.chunfan.mybatis.pojo.Login;
import wang.chunfan.mybatis.pojo.LoginLog;
import wang.chunfan.mybatis.tool.IpUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    LogProducer logProducer;

    @PostMapping
    public String login(@RequestBody Login login) {
        String status;

        LoginLog loginLog = new LoginLog();
        loginLog.setCreateTime(new Date());
        loginLog.setOperation("登录");
        loginLog.setUserId(login.getUserId());
        loginLog.setIp("123");
        // 使用 RequestContextHolder 获取 request, user-agent： 用户访问工具
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        loginLog.setUserAgent(request.getHeader("User-Agent"));
        // 获取用户 ip
        loginLog.setIp(IpUtils.getIpAddr(request));


        if (login.getUserId() == 1 && "1".equals(login.getPassword())) {
            status = "成功";
        } else {
            status = "失败";
        }
        loginLog.setStatus(status);
        // 保存日志
        logProducer.saveLog(loginLog);

        return status;
    }
}
